<?php

namespace App\Http\Controllers;

use App\Http\Models\Item;
use App\Http\Models\Task;
use App\Http\Models\Rank;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class TaskController extends Controller
{

    public function __construct()
    {
        //
    }

    // 接收来伊份请求 更新任务数据
    public function thirdCallUpdateTask(Request $req) {
        $tid = $req->input('tid');
        $uid = $req->input('uid');
        $time = $req->input('time');
        $token = $req->input('token');

        file_put_contents('/tmp/third_call.log', date('Y-m-d H:i:s')."======================================\n".$tid.' - '.$uid.' - '.$time.' - '.$token."\n\n", FILE_APPEND);

        if(!$tid || !$uid || !$time || !$token) return $this->throwError('ErrClientParams');

        $sig_str = 'tid='.$tid.'&time='.$time.'&uid='.$uid.'&secret='.config('game.cfg.BackSecret');
        if(md5($sig_str) != $token) {
            file_put_contents('/tmp/third_call.log', date('Y-m-d H:i:s')."======================================\n".$tid.' - '.$uid.' - '.$time.' - '.$token." sig error\n\n", FILE_APPEND);
            return $this->throwError('ErrSignature');
        }

        $find_user = DB::table('users')->where('openid', $uid)->first();
        if(!isset($find_user['id'])) return $this->throwError('ErrGetUser');

        $tids = explode(',', $tid);
        foreach($tids as $t) {
            // 首单任务判断
            if($t == 602) {
                $uri = '/lyf-user/auth/info';
                $parr = [
                    'lyfuid' => $find_user['openid'],
                    // 'appId' => config('game.cfg.appid'),
                    'appId' => env('APPID'),
                ];
                $lyf_info = curl_call($uri, $parr);
                if(isset($lyf_info['data']['newUser']) && $lyf_info['data']['newUser'] === false) {
                    if($find_user['newUser'] == 1) {
                        Task::setProgress($find_user['id'], $t, 1);
                        DB::table('users')->where('id', $find_user['id'])->update(['newUser'=>0]);
                    }
                }
	        } else if($t == 301 || $t == 302 || $t == 303) {
                Task::setProgress($find_user['id'], $t, 1);
                Task::setProgress($find_user['id'], 2008, 1);
                Task::setProgress($find_user['id'], 2011, 1);
            } else {
                Task::setProgress($find_user['id'], $t, 1);
            }
        }

        return $this->result([]);
    }

    /**
     * 游戏内任务列表
     *
     * @param Request $req
     * @return void
     */
    public function taskInfo(Request $req)
    {
        $uid = \Auth::user();
        if (!$uid) return $this->throwError('ErrUnAuthorization');

        $uinfo = DB::table('users')->where('id', $uid)->first();
        if(!isset($uinfo['id'])) return $this->throwError('ErrGetUser');

        $get_all_task = Task::getTaskConfig();

        $all_tasks = Task::getTaskList( $uid );
        $show_tasks = [];
        foreach($all_tasks as $tid => $task_conf) {
            $show_tasks[] = [
                'confId'  => $tid,
                'type'    => $get_all_task[$tid]['type'],
                'status'  => $task_conf['status'],
                'curr'    => $task_conf['curr'],
                'count'   => $task_conf['count'],
                'name'    => $get_all_task[$tid]['name'],
                'desc'    => $get_all_task[$tid]['desc'],
                'iconUrl' => $get_all_task[$tid]['iconUrl'],
                'jump'    => $get_all_task[$tid]['jump'],
                'target'  => $get_all_task[$tid]['target'],
                'cond'    => $get_all_task[$tid]['cond'],
                'button'  => $get_all_task[$tid]['btn_type'],
                'fodder'  => $task_conf['fodder'],
                'type2'    => intval($get_all_task[$tid]['type2']) ?? 1,
            ];
        }

        return $this->result(['list'=>$show_tasks]);
    }

    public function getTaskStatus(Request $req) {
        $tid = $req->input('tid');
        if(!$tid) return $this->throwError('ErrClientParams');

        $uid = \Auth::user();
        if (!$uid) return $this->throwError('ErrUnAuthorization');

        $uinfo = DB::table('users')->where('id', $uid)->first();
        if(!isset($uinfo['id'])) return $this->throwError('ErrGetUser');

        if($tid == 550) {
            $get_task = DB::table('user_task')->where(['uid'=>$uid, 'tid'=>$tid])->first();

            $uri = '/lyf-user/auth/info';
            $parr = [
                'lyfuid' => $uinfo['openid'],
                // 'appId' => config('game.cfg.appid'),
                'appId' => env('APPID'),
            ];
            $lyf_info = curl_call($uri, $parr);
            file_put_contents('/tmp/1.log', json_encode($lyf_info), FILE_APPEND);
            if(isset($lyf_info['data']['nickName']) && isset($lyf_info['data']['headUrl'])) {
                DB::table('users')->where('id', $uid)->update(['nickName'=>$lyf_info['data']['nickName'], 'avatar'=>$lyf_info['data']['headUrl']]);
                $uinfo['nickName'] = $lyf_info['data']['nickName'];
                $uinfo['avatar'] = $lyf_info['data']['headUrl'];
            }

            $uri = '/supplier-app-api/v1/supplier/portrait/updated';
            if(isset($get_task['status']) && $get_task['status'] != config('game.cfg.TaskStatusUncomplete')) {
                return $this->result([
                    'task_data' => $get_task,
                    'nickName'  => $uinfo['nickName'],
                    'avatar'    => $uinfo['avatar'],
                ]);
            } else {
                $parr = ['lyfuid' => $uinfo['openid']];
                $set_result = curl_call($uri, $parr);
                if (isset($set_result['code']) && $set_result['code'] == 0) {
                    if ($set_result['data'] === true) {
                        Task::setProgress($uid, 550, 1);
                        return $this->result([
                            'task_data' => [
                                'uid' => $uid,
                                'tid' => $tid,
                                'status' => config('game.cfg.TaskStatusCompleted'),
                                'curr' => 1,
                                'count' => 1,
                                'finish' => time(),
                            ],
                            'nickName'  => $uinfo['nickName'],
                            'avatar'    => $uinfo['avatar'],
                        ]);
                    }
                }
                return $this->result([
                    'task_data' => [
                        'uid' => $uid,
                        'tid' => $tid,
                        'status' => config('game.cfg.TaskStatusUncomplete'),
                        'curr' => 0,
                        'count' => 0,
                        'finish' => 0,
                    ],
                    'nickName'  => $uinfo['nickName'],
                    'avatar'    => $uinfo['avatar'],
                ]);
            }
        }

//        else if(in_array($tid, [300,301,302,303,304,602,2002,2005,2008,2011,2014])) {
//
//        }

        else return $this->throwError('ErrClientParams');
    }

    public function getTaskReward(Request $req) {
        $tid = $req->input('tid');
        if(!$tid) return $this->throwError('ErrClientParams');

        $uid = \Auth::user();
        if (!$uid) return $this->throwError('ErrUnAuthorization');

        $uinfo = DB::table('users')->where('id', $uid)->first();
        if(!isset($uinfo['id'])) return $this->throwError('ErrGetUser');

        // 领取奖励
        $tcfg = Task::getTaskConfig( $tid );
        if(empty($tcfg)) return $this->throwError('ErrHasNoTask');
        $tcfg_reward = json_decode($tcfg['reward'], true);

        $task_data = DB::table('user_task')->where(['uid'=>$uid, 'tid'=>$tid])->first();
        if(!isset($task_data['uid'])) {
            $task_data = [
                'uid' => $uid,
                'tid' => $tid,
                'status' => config('game.cfg.TaskStatusUncomplete'),
                'curr' => 0,
                'count' => 0,
                'finish' => 0,
            ];
            $new_tid = DB::table('user_task')->insert($task_data);
            if(!$new_tid) return $this->throwError('ErrCreateTask');
        }

        // 餐点任务直接根据时间段判断，不需要走数据库
        if($tcfg['type'] == config('game.cfg.TaskTypeMeal') && $task_data['status'] != config('game.cfg.TaskStatusReceived')) {
            if(self::nowInTimeRange($tcfg['cond'])) {
                DB::table('user_task')->where(['uid'=>$uid, 'tid'=>$task_data['tid']])->update([
                    'status'=>config('game.cfg.TaskStatusReceived'),
                    'curr' => 1,
                    'count' => 1,
                    'finish' => time(),
                ]);
                $add_rewards = Item::give($uid, $tcfg_reward, $uinfo, 'foodtime_task_'.$tid);
            }
        }
        // 升级任务、普通任务、浏览任务
        else {
            if ($task_data['status'] == config('game.cfg.TaskStatusReceived')) {
                return $this->throwError('ErrTaskAlreadyGet');
            }
            if($task_data['status'] != config('game.cfg.TaskStatusCompleted')) {
                return $this->throwError('ErrTaskReward');
            }

            if ($task_data['count'] >= $tcfg['count']) {
                DB::table('user_task')->where(['uid'=>$uid, 'tid'=>$task_data['tid']])->update(['status'=>config('game.cfg.TaskStatusReceived')]);
                $task_data['status'] = config('game.cfg.TaskStatusReceived');
            } else if ($task_data['count'] <= $tcfg['count']) {

                DB::table('user_task')->where(['uid'=>$uid, 'tid'=>$task_data['tid']])->update([
                    'status' => config('game.cfg.TaskStatusUncomplete'),
                    'curr' => 0,
                    'count' => $tid == 600 ? $task_data['count'] : $task_data['count'] + 1,
                ]);
                $task_data['status'] = config('game.cfg.TaskStatusUncomplete');
            } else {
                return $this->throwError('ErrTaskReward');
            }

            $add_rewards = Item::give($uid, $tcfg_reward, $uinfo, 'task_reward_'.$tid);
        }

        // 判断等级任务
        $level_tasks  = DB::table('game_tasks')->where('type', config('game.cfg.TaskTypeLvup'))->get();
        $get_my_tasks = DB::table('user_task')->where('uid', $uid)->get();
        $my_tasks = [];
        foreach($get_my_tasks as $mt) {
            $my_tasks[$mt['tid']] = $mt;
        }
        $min_level_need = 9999;
        // $select_tid = null;
        foreach($level_tasks as $task_conf) {
            if(isset($my_tasks[$task_conf['id']]) && $my_tasks[$task_conf['id']]['status'] == config('game.cfg.TaskStatusReceived')) continue;
            if($task_conf['cond'] < $min_level_need) {
                $min_level_need = $task_conf['cond'];
            }
        }

        $msg = '';
        if($tcfg['tt'] == 2) {
            // 装扮任务提示msg
            $dress_task = [
                [2000, 2001, 2002],
                [2003, 2004, 2005],
                [2006, 2007, 2008],
                [2009, 2010, 2011],
                [2012, 2013, 2014],
                [2015, 2016, 2017],
            ];
            $count = 1;
            foreach ($dress_task as $dt) {
                if(in_array($tid, $dt)) {
                    foreach($dt as $dtin) {
                        if($dtin == $tid) continue;
                        if(isset($my_tasks[$dtin]) && $my_tasks[$dtin]['status'] == config('game.cfg.TaskStatusReceived')) {
                            $count++;
                        }
                    }
                }
            }
            if($count < 3) $msg = '再解锁'.(3-$count).'个碎片就能获得装扮';
            else $msg = '装扮解锁成功';
        }
        // 活跃度排行榜
        $add_active = 0;
        if(!empty($tcfg_reward)) {
            foreach($tcfg_reward as $r) {
                if($r['type'] == config('game.cfg.ItemTypeFodder')) {
                    $add_active = intval($r['num'] / 10);
                    Rank::set( $uid, $add_active );
                }
            }
        }

        // 检查任务红点
        Task::checkReddot( $uid );

        return $this->result([
            'rewards' => $add_rewards ?? [],
            'next_level_reward' => $min_level_need,
            'tomorrow' => $tcfg['tomorrow'],
            'status' => $task_data['status'],
            'msg' => $msg,
            'add_active' => $add_active,
        ]);
    }

    public function completeTask(Request $req) {
        file_put_contents('/tmp/login_record.log', "FFFFFFFFFFFFFFFFFFFFFFF \n", FILE_APPEND);
        $tid_str = $req->input('tid');
        if(!$tid_str) return $this->throwError('ErrClientParams');

        $uid = \Auth::user();
        if (!$uid) return $this->throwError('ErrUnAuthorization');

        $tids = explode(',', $tid_str);
        foreach($tids as $tid) {
            Task::setProgress($uid, $tid, 1);
        }

        return $this->result([]);
    }

}
